<template>
	<div class="limited">
		<el-row>
			<el-col :span="6">
				<div class="left-box">
					<div class="store-header flex_between">
						<div class="flex_between flex1">
							<div class="bold font_size16">多门店</div>
							<el-switch @change="comBaseSetHandle" v-model="ismshop" :active-value="'1'"
								:inactive-value="'2'"></el-switch>
						</div>
						<template v-if="ismshop == '1'">
							<div class="ml10 mr10 font_black7">|</div>
							<div class="iconBox">
								<text class="icon-font search-icon" @click="addOrEdt">&#xe606;</text>
							</div>
						</template>
					</div>
					<LeftList ref="leftListRef" :templates="templates" :listData="listData"
						:selectedIndex.sync="selectedIndex" :lLoading="lLoading" :lNoMore="lNoMore" @loadFun="loadFun"
						@clickItem="clickItem">
						<div slot-scope="{row}" slot="name" class="flex_between">
							<div>
								<span>{{ row.name }}</span>
								<span class="ml10">{{ row.code_s || '' }}</span>
							</div>
							<el-tag size="mini" :type="row.status == 1 ? '' : 'info'">{{ row.status == 1 ? '启用' : '未启用'
							}}</el-tag>
						</div>
						<div slot-scope="{row}" slot="address" class="flex_between mb5">
							<span class="font_black7 mr10">{{ row.district || '' }}{{ row.address || '' }}</span>
							<el-tag type="warning" size="mini" v-if="row.base == 1"> 初始门店 </el-tag>
						</div>
					</LeftList>
				</div>
			</el-col>
			<el-col :span="18">
				<div class="rigth-box">
					<div class="rigth-box-content">
						<el-form ref="formRef" :model="objectForm" :rules="objectRules" label-width="140px">
							<el-form-item label="门店图标">
								<div class="active-box">
									<UploadPhotos :list="photoList" @update:list="updatePhotoList" :limit="1" />
								</div>
							</el-form-item>
							<el-form-item label="门店名称" prop="name">
								<el-input v-model="objectForm.name" class="input-w" placeholder="请填写企业名称" maxlength="50"
									show-word-limit></el-input>
							</el-form-item>
							<el-form-item label="门店缩写" prop="code_s">
								<el-input type="text" v-model="objectForm.code_s" class="input-w" placeholder="门店缩写"
									show-word-limit></el-input>
							</el-form-item>
							<el-form-item label="所在地区" prop="district">
								<el-cascader id="selectPrCtAr" v-model="objectForm.districtCodeArr"
									:options="optionsPosition" :props="propsdata" placeholder="省市区"
									@change="handleChange" class="input-w">
								</el-cascader>
							</el-form-item>
							<el-form-item label="详细地址" prop="address">
								<el-input type="text" v-model="objectForm.address" class="input-w"
									placeholder="门店缩写"></el-input>
							</el-form-item>
							<el-form-item label="启用门店" prop="status">
								<el-switch v-model="objectForm.status" :active-value="'1'"
									:inactive-value="'2'"></el-switch>
							</el-form-item>
						</el-form>
					</div>
					<div class="rigth-box-footer flex_between">
						<div class="summary-info"></div>
						<div class="action-buttons">
							<el-button type="primary" @click="sbumitHandle" size="large" class="btn-confirm"> 保 存
							</el-button>
						</div>
					</div>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from '@vue/composition-api'
import LeftList from "@/pages/setting/components/leftList.vue"
import config from "@/js/conf/Config.js"
import API from "@/js/conf/api.js"
import { useCommonHooks } from '@/hooks/useCommonHooks.js'
import UploadPhotos from "@/components/commV2/UploadPhotos/index.vue"

// 使用全局状态
const { stateHooks } = useCommonHooks()

const maxPnum = 20
// 获取当前组件实例
const { proxy } = getCurrentInstance()

const templates = ref([{
	type: "slot",
	key: "name",
}, {
	type: "slot",
	key: "address",
},
])
const ismshop = ref('1')
const photoList = ref([])
// 表单数据
const objectForm = ref({
	address: '',
	atme: '',
	base: 1,
	codes: '',
	district: '',
	districtCodeArr: [],
	id: 1,
	imgs: '',
	name: '',
	code_s: '',
	status: '1',
})
const detailID = ref('')

// 表单验证规则
const objectRules = ref({
	name: [
		{ required: true, message: '请输入门店名称', trigger: 'blur' }
	],
	code_s: [
		{ required: true, message: '请输入门店缩写', trigger: 'blur' }
	],
	districtCodeArr: [
		{ required: true, message: '请选择所在地区', trigger: 'change' }
	],
	address: [
		{ required: true, message: '请输入详细地址', trigger: 'blur' }
	],
})

const listData = ref([])
const selectedIndex = ref(0)
const pfrom = ref(0)
const lLoading = ref(false)
const lNoMore = ref(false)

const loadFun = () => {
	if (lNoMore.value || lLoading.value) return
	pfrom.value += 20
	if (listData.value.length > 0) {
		pfrom.value += 20
		getEventLs(false)
	}
}

const getEventLs = async (t = true) => {
	lLoading.value = true
	if (t == true) {
		pfrom.value = 0
		listData.value = []
	}
	let param = {
		issell: 0,
		status: 0,
	}
	try {
		let res = await proxy.$api({ url: config.company_shop_ls_2set, data: param })
		lLoading.value = false
		if (res.status == 1) {
			let result = res.data
			if (result && result.length > 0) {
				listData.value.push(...result)
				// 确保索引在有效范围内
				const validIndex = Math.min(selectedIndex.value, listData.value.length - 1)
				if (t == true) {
					detailID.value = listData.value[validIndex]?.id
					getShopInfo()
				}
				if (res.status == 1 && result.ls.length < maxPnum) {
					lNoMore.value = true
				} else {
					lNoMore.value = false
				}
			} else {
				lNoMore.value = true;
			}
		} else {
			lNoMore.value = true
		}
	} catch (error) {
		lLoading.value = false
		lNoMore.value = true
	} finally {
		lLoading.value = false
	}
}

const getShopInfo = async () => {
	try {
		let res = await proxy.$api({
			url: config.company_shop_info, data: {
				id: detailID.value
			}
		})
		let result = res.data || {}
		if (res.status == 1) {
			objectForm.value = result
			photoList.value = result.imgs ? [{ url: result.imgs }] : []
			// 正确设置省市区代码数组
			const districtCodes = []
			if (result.province) districtCodes.push(result.province)
			if (result.city) districtCodes.push(result.city)
			if (result.area) districtCodes.push(result.area)
			objectForm.value.districtCodeArr = districtCodes
		}
	} catch (error) {
		console.error('获取门店信息失败:', error)
	} finally {
	}
}

const comBaseSetHandle = async () => {
	try {
		let res = await proxy.$api({
			url: config.compset_base_set, data: {
				ismshop: ismshop.value
			}
		})
		if (res.status == 1) {
			getEventLs()
		}
	} catch (error) {
		console.error('获取门店信息失败:', error)
	}
}


const clickItem = (index) => {
	detailID.value = listData.value[index]?.id
	getShopInfo()
}

const addOrEdt = () => {
	resetFun()
	detailID.value = 0
	selectedIndex.value = null
}

const resetFun = () => {
	objectForm.value = {
		address: '',
		atme: '',
		base: 1,
		codes: '',
		district: '',
		districtCodeArr: [],
		id: 0,
		imgs: '',
		name: '',
		code_s: '',
		status: '1',
	}
	photoList.value = []
}

const updatePhotoList = (newList) => {
	photoList.value = newList
}

const optionsPosition = ref([]) //省市区列表
const propsdata = ref({
	children: "cityList",
	label: "name",
	value: "code",
	expandTrigger: "hover",
	checkStrictly: true,
}) //省市区列表

// 获取省市区
const getdistrictsData = async () => {
	let res = await proxy.$api({ url: config.COMM_DISTRICTS, data: {} });
	if (!res) return;
	if (res.status == 1 && res.data) {
		optionsPosition.value = res.data;
	}
}

const handleChange = (value) => {
	console.log('省市区选择变化:', value)
	// 级联选择器自动更新 objectForm.districtCodeArr
	// 同时更新地区名称字符串
	if (value && value.length > 0) {
		objectForm.value.district = getmapNameFun(value)
	} else {
		objectForm.value.district = ''
	}
}

// 获取地址名称
const getmapNameFun = (arr) => {
	let name = "";
	const province = arr[0] | "";
	const city = arr[1] | "";
	const area = arr[2] | "";
	if (province) {
		optionsPosition.value.map((v) => {
			if (province == v.code) {
				name += v.name;
				if (city) {
					v.cityList.map((vs) => {
						if (city == vs.code) {
							name += vs.name;
							if (area) {
								vs.cityList.map((vw) => {
									if (area == vw.code) {
										name += vw.name;
									}
								});
							}
						}
					});
				}
			}
		});
	}
	return name;
}

const sbumitHandle = async () => {
	try {
		// 表单验证
		const valid = await proxy.$refs.formRef.validate()
		if (!valid) {
			proxy.$message({
				message: '请完善表单信息',
				type: 'warning'
			})
			return
		}
		const districtArr = objectForm.value.districtCodeArr || []
		let params = {
			...objectForm.value,
			province: districtArr[0] || "",
			city: districtArr[1] || "",
			area: districtArr[2] || "",
			imgs: photoList.value.length > 0 ? photoList.value[0].name : ''
		}
		let res = await proxy.$api({ url: config.company_shop_save, data: params })
		if (res.status == 1) {
			proxy.$message({
				message: '保存成功',
				type: 'success'
			})
			getEventLs()
		} else {
			proxy.$message({
				message: res.msg || '保存失败',
				type: 'error'
			})
		}
	} catch (error) {
		console.error('保存失败:', error)
		proxy.$message({
			message: '请检查表单内容',
			type: 'error'
		})
	}
}

onMounted(async () => {
	let res = await API.get_compset_base_info()
	if (res.status == 1) {
		ismshop.value = res.data.ismshop
	}
	await getdistrictsData()
	getEventLs()
})

</script>

<style lang="scss" scoped>
div {
	box-sizing: border-box;
}

.limited {
	max-height: 100vh;
	height: calc(100vh - 90px);
	/* 确保最小高度为视窗高度 */
	overflow: hidden;

	::v-deep .el-row {
		height: 100%;
	}

	::v-deep .el-col {
		height: 100%;
	}

	.left-box,
	.rigth-box {
		width: 100%;
		padding: 0 10px 0 10px;
		height: 100%;

		.iconBox {
			font-size: 26px;
			cursor: pointer;
			position: relative;
			top: -6px;

			.search-icon {
				font-size: 20px;
				color: #333;
			}
		}
	}

	.left-box {
		border-right: 1px solid #e6e6e6;

		.store-header {
			box-sizing: border-box;
			border: 1px solid #f1f1f1;
			border-radius: 4px;
			box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
			padding: 0 14px;
			height: 60px;
		}
	}

	.rigth-box {
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		height: 100%;
		/* 确保容器有明确高度 */
		overflow: hidden;

		.rigth-box-content {
			box-sizing: border-box;
			flex: 1;
			height: 0;
			/* 关键：让flex-grow生效 */
			min-height: 0;
			/* 允许收缩 */
			padding-right: 100px;
			overflow-y: auto;
			/* 内容溢出时显示滚动条 */
		}

		.rigth-box-footer {
			flex-shrink: 0;
			/* 防止footer被压缩 */
			border-top: 1px solid #f1f1f1;
			margin-top: 10px;
			padding: 14px 10px 4px;

			.summary-info {
				display: flex;
				align-items: center;
				gap: 16px;
			}

			.action-buttons {
				display: flex;
				gap: 12px;

				.btn-cancel {
					border-color: #cbd5e1;
					color: #64748b;
				}

				.btn-confirm {
					background-color: #3b82f6;
					border-color: #3b82f6;
				}
			}
		}
	}
}

.input-w {
	width: 400px;
}
</style>